﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using SimpleBlog.Infrastructure.Repositories;
using SimpleBlog.Helpers;
using SimpleBlog.Mvc;

namespace SimpleBlog.Controllers
{
    public class FeedController : Controller
    {
        IPostRepository _postRepository;
        IConfigurationRepository _configurationRepository;

        public FeedController(IPostRepository postRepository, IConfigurationRepository configurationRepository)
        {
            _postRepository = postRepository;
            _configurationRepository = configurationRepository;
        }

        [HttpGet]
        public ActionResult Index()
        {
            //get database info
            var firstPost = _postRepository.GetAll(0, 1, x => x.Created, false).FirstOrDefault();
            var firstDate = firstPost == null ? DateTime.MinValue : firstPost.Created;
            var posts = _postRepository.GetAll(0, 20);

            XDocument data = new XDocument();
            XNamespace atom = "http://www.w3.org/2005/Atom";

            //declaration
            data.Declaration = new XDeclaration("1.0", "utf-8", "yes");
            data.Add(new XElement("rss", new XAttribute("version", "2.0"), new XAttribute(XNamespace.Xmlns + "atom", atom)));

            //channel
            var channel = new XElement("channel");
            data.Root.Add(channel);
            channel.Add(new XElement(atom + "link",
                                new XAttribute("href", this.Request.Url),
                                new XAttribute("rel", "self"),
                                new XAttribute("type", "application/rss+xml")));
            channel.Add(new XElement("title", _configurationRepository.BlogTitle));
            channel.Add(new XElement("link", this.Request.GetAbsoluteUrl("")));
            channel.Add(new XElement("description", HttpUtility.HtmlDecode(_configurationRepository.AboutText).Strip())); //Get only text
            channel.Add(new XElement("pubDate", firstDate.ToString("r")));
            channel.Add(new XElement("lastBuildDate", DateTime.UtcNow.ToString("r")));

            //items
            XElement item = null;
            foreach (var post in posts)
            {
                //generate item
                item = new XElement("item");
                item.Add(new XElement("title", post.Title));
                item.Add(new XElement("link", this.Request.GetAbsoluteUrl("/Post/" + post.EncodedTitle)));
                item.Add(new XElement("description", post.Text));
                item.Add(new XElement("pubDate", post.Created.ToString("r")));
                item.Add(new XElement("guid", this.Request.GetAbsoluteUrl("/Post/" + post.EncodedTitle)));
                //add item
                channel.Add(item);
            }

            return new XmlResult(data, true);
        }
    }
}
